<template>
  <div class="page-container">
    <h2 class="page-title">老店管理</h2>

    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" class="search-form" label-width="90px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="门店名称">
              <el-input v-model="searchForm.storeName" placeholder="请输入门店名称" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="所在城市">
              <el-input v-model="searchForm.storeAddress" placeholder="请输入城市" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="提交人">
              <el-input v-model="searchForm.submitter" placeholder="请输入提交人" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="加盟商姓名">
              <el-input v-model="searchForm.franchisee" placeholder="请输入加盟商姓名" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8">
            <el-form-item label="加盟商电话">
              <el-input v-model="searchForm.franchiseePhone" placeholder="请输入加盟商电话" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" class="search-btns-col">
            <el-form-item label-width="0">
              <div class="search-btns">
                <el-button type="primary" @click="onSearch" icon="el-icon-search">查询</el-button>
                <el-button @click="onReset" icon="el-icon-refresh">重置</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>门店列表</span>
        </div>
      </template>
      <el-table :data="tableData" style="width: 100%" stripe v-loading="loading" element-loading-text="正在加载数据...">
        <el-table-column prop="storeName" label="门店名称" />
        <el-table-column prop="storeAddress" label="所在城市" />
        <el-table-column prop="submitter" label="提交人" />
        <el-table-column prop="franchisee" label="加盟商姓名" />
        <el-table-column prop="franchiseePhone" label="加盟商电话" />
        <el-table-column prop="eleme_pingtuan" label="饿了么拼团" align="center">
          <template #default="scope">
            <el-tag v-if="toZeroOne(scope.row.eleme_pingtuan) === 1" type="success" effect="plain">有</el-tag>
            <el-tag v-else type="info" effect="plain">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="420" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                type="primary"
                link
                size="small"
                icon="el-icon-edit"
                @click="onViewDetail(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                link
                size="small"
                icon="el-icon-document"
                @click="onEdit(scope.row)"
              >
                查看详情
              </el-button>
              <el-select
                v-model="scope.row.closeStore"
                size="small"
                style="width: 90px;"
                placeholder="店铺状态"
                @change="onStatusChange(scope.row)"
              >
                <el-option label="开店" :value="1" />
                <el-option label="闭店" :value="0" />
              </el-select>
              <el-button
                type="success"
                link
                size="small"
                icon="el-icon-share"
                @click="onHandover(scope.row)"
              >
                门店交接
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model="pageNum"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          layout="total, prev, pager, next, jumper"
          class="custom-pagination"
        />
      </div>
    </el-card>
    <el-dialog v-model="viewDialogVisible" title="编辑老店" width="540px" class="oldstore-view-dialog custom-view-dialog">
      <div v-if="viewDetail" class="oldstore-view-content custom-view-content">
        <el-form :model="editForm" label-width="110px" class="custom-edit-form">
          <el-form-item v-for="(value, key) in displayDetail" :key="key" :label="fieldLabels[key] || key">
            <template v-if="key === 'joinDate' || key === 'join_date'">
              <el-date-picker
                v-model="editForm[key]"
                type="date"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                placeholder="选择加盟日期"
                style="width: 260px;"
                :editable="false"
                :clearable="true"
              />
            </template>
            <template v-else-if="['closeStore', 'close_store'].includes(key)">
              <el-select v-model="editForm[key]" style="width: 120px" @change="onCloseStoreChange">
                <el-option label="开店" :value="1" />
                <el-option label="闭店" :value="0" />
              </el-select>
            </template>
            <template v-else-if="key === 'eleme_pingtuan'">
              <el-select v-model="editForm[key]" style="width: 120px">
                <el-option :value="1" label="有" />
                <el-option :value="0" label="否" />
              </el-select>
            </template>
            <template v-else-if="['sharpshooter', 'pinghaofan'].includes(key)">
              <el-select v-model="editForm[key]" style="width: 120px">
                <el-option :value="1" label="是" />
                <el-option :value="0" label="否" />
              </el-select>
            </template>
            <template v-else-if="['description', 'remarks'].includes(key)">
              <el-input
                v-model="editForm[key]"
                type="textarea"
                :rows="4"
                :autosize="{ minRows: 3, maxRows: 8 }"
                class="custom-textarea"
                placeholder="请输入内容"
              />
            </template>
            <template v-else-if="key === 'closeTime' && editForm.closeStore === 0">
              <el-date-picker
                v-model="editForm[key]"
                type="date"
                placeholder="闭店时间"
                format="YYYY-MM-DD"
                disabled
                style="width: 260px;"
              />
            </template>
            <template v-else-if="key !== 'closeTime'">
              <el-input v-model="editForm[key]" />
            </template>
          </el-form-item>
        </el-form>
      </div>
      <div v-else class="oldstore-edit-empty">暂无数据</div>
      <template #footer>
        <div class="oldstore-edit-footer custom-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="onEditDetailSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="editDialogVisible" title="门店交接详情" width="480px" class="oldstore-edit-dialog">
      <div v-if="editDetail" class="oldstore-edit-content">
        <el-form :model="editDetail" label-width="90px">
          <el-form-item label="店名">
            <el-input v-model="editDetail.storeName" placeholder="请输入店名" />
          </el-form-item>
          <el-form-item label="提交者">
            <el-input v-model="editDetail.submitter" placeholder="请输入提交者" />
          </el-form-item>
          <el-form-item label="提交时间">
            <el-input :value="formatDateTime(editDetail.submitTime)" readonly />
          </el-form-item>
          <el-form-item label="接收者">
            <el-input v-model="editDetail.receiver" placeholder="请输入接收者" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="editDetail.remarks" type="textarea" :rows="2" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-input :value="formatDateTime(editDetail.createTime)" readonly />
          </el-form-item>
        </el-form>
      </div>
      <div v-else class="oldstore-edit-empty">暂无数据</div>
      <template #footer>
        <div class="oldstore-edit-footer">
          <el-button @click="editDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="onEditSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 门店交接弹窗 -->
    <el-dialog v-model="handoverDialogVisible" title="门店交接" width="400px">
      <div class="handover-content">
        <el-form :model="handoverForm" label-width="100px">
          <el-form-item label="门店名称">
            <el-input v-model="handoverForm.storeName" readonly />
          </el-form-item>
          <el-form-item label="选择交接人" required>
            <el-select 
              v-model="handoverForm.managerId" 
              placeholder="请选择交接人"
              style="width: 100%;"
              filterable
            >
              <el-option 
                v-for="employee in employee4List" 
                :key="employee.employeeId" 
                :label="`${employee.name} (${employee.account})`" 
                :value="employee.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="handover-footer">
          <el-button @click="handoverDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandover" :loading="isHandovering">
            {{ isHandovering ? '交接中...' : '确认交接' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { useUserStore } from '@/store/user';
import { ElMessage, ElMessageBox } from 'element-plus';

const userStore = useUserStore();

const searchForm = ref({
  storeName: '',
  storeAddress: '',
  submitter: '',
  franchisee: '',
  franchiseePhone: ''
});

const tableData = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(15);
const loading = ref(false); // 添加loading状态

function fetchTableData() {
  loading.value = true; // 开始加载
  
  // 新接口 POST http://121.43.176.9:8090/oldStore/search?userId=xxx&page=1&size=10
  const params = new URLSearchParams({
    userId: userStore.userId,
    page: pageNum.value,
    size: pageSize.value
  });
  fetch(`http://121.43.176.9:8090/oldStore/search?${params.toString()}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(searchForm.value)
  })
    .then(r => r.json())
    .then(async res => {
      if (res.records) {
        // 为每个门店获取提交时间并排序
        const sortedData = await getSortedTableData(res.records);
        tableData.value = sortedData;
        total.value = res.total || 0;
      } else {
        tableData.value = [];
        total.value = 0;
      }
    })
    .catch(error => {
      console.error('获取数据失败:', error);
      ElMessage.error('获取数据失败');
      tableData.value = [];
      total.value = 0;
    })
    .finally(() => {
      loading.value = false; // 结束加载
    });
}

// 获取排序后的表格数据
async function getSortedTableData(records) {
  try {
    // 为每个门店获取提交时间
    const dataWithSubmitTime = [];
    const submitTimeCache = new Map(); // 添加缓存
    
    for (const record of records) {
      try {
        let submitTime = null;
        
        // 检查缓存
        if (submitTimeCache.has(record.storeId)) {
          submitTime = submitTimeCache.get(record.storeId);
        } else {
          // 获取门店的提交时间（从查看详情接口获取）
          const submitTimeRes = await fetch(`http://121.43.176.9:8090/api/store-handover/oldStoreEdit?storeId=${record.storeId}`).then(r => r.json());
          
          if (submitTimeRes.code === 200 && submitTimeRes.data && submitTimeRes.data.submitTime) {
            submitTime = new Date(submitTimeRes.data.submitTime).getTime();
            // 缓存结果
            submitTimeCache.set(record.storeId, submitTime);
          }
        }
        
        dataWithSubmitTime.push({
          ...record,
          submitTimeValue: submitTime
        });
      } catch (error) {
        console.error('获取门店提交时间失败:', error);
        // 如果获取失败，使用默认值（排在最后）
        dataWithSubmitTime.push({
          ...record,
          submitTimeValue: 0
        });
      }
    }
    
    // 首先按店铺状态排序：开店(1)在前，闭店(0)在后
    // 然后按提交时间排序，时间越靠后的排在越前面
    dataWithSubmitTime.sort((a, b) => {
      // 首先按店铺状态排序
      if (a.closeStore !== b.closeStore) {
        return b.closeStore - a.closeStore; // 开店(1)在前，闭店(0)在后
      }
      
      // 状态相同时，按提交时间排序
      const timeA = a.submitTimeValue || 0;
      const timeB = b.submitTimeValue || 0;
      return timeB - timeA; // 降序排列，最新的在前
    });
    
    // 移除临时的submitTimeValue字段
    return dataWithSubmitTime.map(item => {
      const { submitTimeValue, ...rest } = item;
      return rest;
    });
    
  } catch (error) {
    console.error('排序处理失败:', error);
    return records; // 如果排序失败，返回原始数据
  }
}

onMounted(() => {
  fetchTableData();
  fetchEmployee4List();
});

// 获取permission_type为4的员工列表
async function fetchEmployee4List() {
  try {
    const res = await fetch('http://121.43.176.9:8090/api/employee/employee4-list').then(r => r.json());
    if (res.code === 200) {
      employee4List.value = res.data || [];
    } else {
      employee4List.value = [];
    }
  } catch (error) {
    console.error('获取员工列表失败:', error);
    employee4List.value = [];
  }
}

function handlePageChange(val) {
  pageNum.value = val;
  fetchTableData();
}

function onSearch() {
  pageNum.value = 1;
  fetchTableData();
}
function onReset() {
  searchForm.value = {
    storeName: '',
    storeAddress: '',
    submitter: '',
    franchisee: '',
    franchiseePhone: ''
  };
  pageNum.value = 1;
  fetchTableData();
}
function formatDate(val) {
  return formatDateTime(val);
}
function formatDateTime(val) {
  if (!val) return '-';
  const d = new Date(val);
  if (isNaN(d)) return '-';
  return d.toLocaleString();
}
const editDialogVisible = ref(false);
const editDetail = ref(null);
const viewDialogVisible = ref(false);
const viewDetail = ref(null);

// 门店交接相关
const handoverDialogVisible = ref(false);
const handoverForm = ref({
  storeId: '',
  storeName: '',
  managerId: null
});
const employee4List = ref([]);
const isHandovering = ref(false);
const hiddenFields = ['id', 'storeId', 'store_id', 'managerId', 'employee1'];
const displayDetail = computed(() => {
  if (!viewDetail.value) return {};
  const result = {};
  for (const key in viewDetail.value) {
    if (!hiddenFields.includes(key)) {
      // 如果是闭店状态，显示closeTime字段；如果是开店状态，隐藏closeTime字段
      if (key === 'closeTime') {
        if (viewDetail.value.closeStore === 0) {
          result[key] = viewDetail.value[key];
        }
      } else {
        result[key] = viewDetail.value[key];
      }
    }
  }
  return result;
});
const fieldLabels = {
  id: '', // 不显示
  storeId: '店铺ID',
  store_id: '店铺ID',
  storeName: '店铺名字',
  store_name: '店铺名字',
  storeAddress: '店铺地址',
  store_address: '店铺地址',
  submitter: '提交人',
  manager: '管理人',
  franchisee: '加盟商',
  franchiseePhone: '加盟商电话',
  franchisee_phone: '加盟商电话',
  meituanStoreId: '美团门店ID',
  meituan_store_id: '美团门店ID',
  storeLocation1: '门店所在1',
  store_location1: '门店所在1',
  elemeStoreId: '饿了么门店ID',
  eleme_store_id: '饿了么门店ID',
  storeLocation2: '门店所在2',
  store_location2: '门店所在2',
  jdAccount: '京东账号',
  jd_account: '京东账号',
  jdStoreId: '京东ID',
  jd_store_id: '京东ID',
  description: '情况说明',
  remarks: '备注',
  closeStore: '店铺状态',
  close_store: '店铺状态',
  closeTime: '闭店时间',
  sharpshooter: '神枪手',
  pinghaofan: '拼好饭',
  eleme_pingtuan: '饿了么拼团',
  joinDate: '加盟日期',
  join_date: '加盟日期',
};
function onEdit(row) {
  // 只弹编辑弹窗
  fetch(`http://121.43.176.9:8090/api/store-handover/oldStoreEdit?storeId=${row.storeId}`)
    .then(r => r.json())
    .then(res => {
      if (res.code === 200 && res.data) {
        // 打开“门店交接详情”时，也将 eleme_pingtuan 规范成 0/1，保证显示一致
        editDetail.value = {
          ...res.data,
          eleme_pingtuan: toZeroOne(res.data.eleme_pingtuan)
        };
        editDialogVisible.value = true;
      } else {
        ElMessage.error(res.msg || '获取详情失败');
      }
    });
}
function onViewDetail(row) {
  // Create a deep copy to avoid mutating original table data
  const rowCopy = JSON.parse(JSON.stringify(row));

  // 规范化饿了么拼团字段，确保下拉初始选择与接口一致
  rowCopy.eleme_pingtuan = toZeroOne(rowCopy.eleme_pingtuan);

  // 如果店铺状态为开店且没有闭店时间，设置默认值
  if (rowCopy.closeStore === 1 && !rowCopy.closeTime) {
    rowCopy.closeTime = null;
  }

  // 处理后端返回的Date格式数据
  if (rowCopy.closeTime && typeof rowCopy.closeTime === 'string') {
    const closeDate = new Date(rowCopy.closeTime);
    closeDate.setHours(0, 0, 0, 0); // 设置时间为00:00:00，只保留年月日
    rowCopy.closeTime = closeDate;
  }

  // Populate the form's data model with the copy
  Object.keys(editForm).forEach(key => delete editForm[key]); // Clear old data
  Object.assign(editForm, rowCopy);

  // Set viewDetail which is used by the displayDetail computed property to render the form.
  viewDetail.value = rowCopy;

  viewDialogVisible.value = true;
}
function onStatusChange(row) {
  const newStatusText = row.closeStore === 1 ? '开店' : '闭店';
  ElMessageBox.confirm(`确定要将店铺状态更新为"${newStatusText}"吗？`, '状态变更确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 如果状态变为闭店，自动设置闭店时间（只保留年月日）
    if (row.closeStore === 0) {
      const today = new Date();
      row.closeTime = today; // 使用Date对象，后端会处理时区
    }
    // 如果状态变为开店，清空闭店时间
    if (row.closeStore === 1) {
      row.closeTime = null;
    }
    
    // 规范化 eleme_pingtuan 并一并传入
    const payload = {
      ...row,
      eleme_pingtuan: row.eleme_pingtuan !== undefined ? toZeroOne(row.eleme_pingtuan) : row.eleme_pingtuan,
    };
    fetch('http://121.43.176.9:8090/oldStore/edit', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    })
    .then(res => res.ok ? res.json() : Promise.reject(new Error('网络响应错误')))
    .then(success => {
      if (success) {
        ElMessage.success('状态更新成功');
        fetchTableData(); // 刷新以确认状态
        
        // 新增：当用户选择闭店时，调用/api/log/add接口
        if (row.closeStore === 0) {
          const log = {
            storeId: row.storeId,
            submitFrom: userStore.account,
            submitTo: '-',
            submitTime: new Date().toISOString(),
            stage: 7
          };
          fetch('http://121.43.176.9:8090/api/log/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(log)
          }).catch(err => {
            console.error('日志记录失败:', err);
          });
          
          // 创建闭店提醒（不区分员工）
          // 确保closeDate是字符串格式
          let closeDateStr = null;
          if (row.closeTime) {
            if (row.closeTime instanceof Date) {
              closeDateStr = row.closeTime.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
            } else if (typeof row.closeTime === 'string') {
              closeDateStr = row.closeTime.split('T')[0]; // 如果是ISO字符串，取日期部分
            } else {
              closeDateStr = row.closeTime;
            }
          }
          
          const reminder = {
            storeId: row.storeId,
            closeDate: closeDateStr
          };

          fetch('http://121.43.176.9:8090/api/store-close-reminder/create', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(reminder)
          })
          .then(response => {
            if (!response.ok) {
              throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
          })
          .then(data => {
            if (data.code === 200) {
            } else {
              console.error('闭店提醒创建失败:', data.msg);
            }
          })
          .catch(err => {
            console.error('创建闭店提醒失败:', err);
          });
        }
      } else {
        ElMessage.error('状态更新失败');
        fetchTableData(); // 刷新以恢复原状态
      }
    })
    .catch(err => {
      ElMessage.error(`请求失败: ${err.message}`);
      fetchTableData(); // 刷新以恢复原状态
    });
  }).catch(() => {
    ElMessage.info('操作已取消');
    fetchTableData(); // 用户取消操作，刷新表格以恢复更改前的状态
  });
}
function onEditSubmit() {
  ElMessageBox.confirm('确定要提交修改吗？', '确认修改', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 实际提交请求
    fetch('http://121.43.176.9:8090/api/store-handover/update', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(editDetail.value)
    })
      .then(r => r.json())
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('提交成功');
          editDialogVisible.value = false;
        } else {
          ElMessage.error(res.msg || '提交失败');
        }
      })
      .catch(() => {
        ElMessage.error('提交失败');
      });
  });
}
function onViewSubmit() {
  ElMessageBox.confirm('确定要提交吗？', '确认提交', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 实际提交请求
    fetch('http://121.43.176.9:8090/api/store-handover/oldStoreEdit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(viewDetail.value)
    })
      .then(r => r.json())
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('提交成功');
          viewDialogVisible.value = false;
        } else {
          ElMessage.error(res.msg || '提交失败');
        }
      })
      .catch(() => {
        ElMessage.error('提交失败');
      });
  });
}
const editForm = reactive({});

// 将“是/否、布尔、字符串”统一规范到 0/1（否=0，是=1）
function toZeroOne(value) {
  if (value === 1 || value === '1' || value === true || value === '是') {
    return 1;
  }
  if (value === 0 || value === '0' || value === false || value === '否') {
    return 0;
  }
  return value;
}

// 处理店铺状态变更
function onCloseStoreChange(value) {
  if (value === 0) {
    // 状态变为闭店，设置默认闭店时间（只保留年月日）
    const today = new Date();
    editForm.closeTime = today; // 使用Date对象，后端会处理时区
  } else {
    // 状态变为开店，清空闭店时间
    editForm.closeTime = null;
  }
}

function onEditDetailSubmit() {
  ElMessageBox.confirm('确定要提交修改吗？', '确认修改', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    // 确保传入 eleme_pingtuan 字段，并统一成 0/1
    const payload = {
      ...editForm,
      eleme_pingtuan: editForm.eleme_pingtuan !== undefined ? toZeroOne(editForm.eleme_pingtuan) : editForm.eleme_pingtuan,
    };
    fetch('http://121.43.176.9:8090/oldStore/edit', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    })
    .then(res => {
      // The backend returns a simple boolean.
      if (res.ok) {
        return res.json();
      } else {
        throw new Error('网络错误，无法连接到服务器');
      }
    })
    .then(success => {
      if (success) {
        ElMessage.success('修改成功');
        viewDialogVisible.value = false;
        fetchTableData(); // Refresh the table to show updated data
      } else {
        ElMessage.error('修改失败，请检查提交的数据');
      }
    })
    .catch(error => {
      ElMessage.error(`请求失败: ${error.message}`);
    });
  });
}

// 门店交接相关方法
function onHandover(row) {
  handoverForm.value = {
    storeId: row.storeId,
    storeName: row.storeName,
    managerId: null
  };
  handoverDialogVisible.value = true;
}

async function submitHandover() {
  if (!handoverForm.value.managerId) {
    ElMessage.warning('请选择交接人');
    return;
  }
  
  isHandovering.value = true;
  try {
    const params = new URLSearchParams({
      storeId: handoverForm.value.storeId,
      managerId: handoverForm.value.managerId
    });
    
    const res = await fetch(`http://121.43.176.9:8090/oldStore/handover?${params.toString()}`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    }).then(r => r.json());
    
    if (res.code === 200) {
      ElMessage.success('门店交接成功');
      handoverDialogVisible.value = false;
      fetchTableData(); // 刷新表格数据
    } else {
      ElMessage.error(res.msg || '门店交接失败');
    }
  } catch (error) {
    console.error('门店交接失败:', error);
    ElMessage.error('门店交接失败，请重试');
  } finally {
    isHandovering.value = false;
  }
}
</script>

<style scoped>
.page-container {
  padding: 24px;
  background-color: #f5f7fa;
}
.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
}
.search-card, .table-card {
  border-radius: 8px;
  margin-bottom: 24px;
  background-color: #fff;
}
.search-btns-col {
  display: flex;
  justify-content: flex-end;
}
.search-btns {
  display: flex;
  gap: 12px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 17px;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}
.action-buttons .el-button.is-link {
  font-size: 14px;
}
.oldstore-search-card {
  margin-bottom: 18px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
  background: #f8fafd;
}
.oldstore-search-form {
  padding: 8px 0 0 0;
}
.oldstore-search-btns-col {
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
}
.oldstore-search-btns {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  width: 100%;
}
.oldstore-batch-bar {
  margin: 10px 0 0 0;
  display: flex;
  justify-content: flex-start;
}
.oldstore-batch-bar-bottom {
  margin: 16px 0 0 0;
  display: flex;
  justify-content: flex-start;
}
.oldstore-pagination {
  display: flex;
  justify-content: flex-end;
}
.oldstore-edit-dialog .el-dialog__body {
  padding: 24px 32px 12px 32px;
  background: #f8fafd;
}
.oldstore-edit-content {
  margin-bottom: 8px;
}
.oldstore-edit-empty {
  text-align: center;
  color: #999;
  font-size: 16px;
  padding: 32px 0 24px 0;
}
.oldstore-edit-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.desc-value {
  font-weight: 500;
  color: #222;
}
.oldstore-view-dialog .el-dialog__body {
  padding: 24px 32px 12px 32px;
  background: #f8fafd;
}
.oldstore-view-content {
  margin-bottom: 8px;
}
.custom-view-dialog >>> .el-dialog__header {
  font-size: 22px;
  font-weight: bold;
  letter-spacing: 1px;
  color: #2d3a4b;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 12px;
}
.custom-view-content {
  padding: 18px 8px 8px 8px;
  background: #fafdff;
  border-radius: 8px;
}
.custom-descriptions {
  margin-bottom: 0;
  font-size: 16px;
}
.custom-descriptions >>> .el-descriptions-item__label {
  font-weight: 500;
  color: #3a3a3a;
  background: #f5f7fa;
  width: 120px;
}
.custom-descriptions >>> .el-descriptions-item__content {
  color: #222;
  font-size: 16px;
  padding-left: 12px;
}
.custom-value {
  font-weight: 400;
  color: #222;
}
.custom-footer {
  display: flex;
  justify-content: flex-end;
  gap: 18px;
  padding-top: 8px;
}
.custom-desc-item {
  margin-bottom: 10px;
  font-size: 17px;
}
.custom-descriptions >>> .el-descriptions-item__label {
  font-weight: bold;
  color: #2d3a4b;
  background: #f5f7fa;
  width: 130px;
  font-size: 17px;
}
.custom-descriptions >>> .el-descriptions-item__content {
  color: #222;
  font-size: 17px;
  padding-left: 16px;
}
.bool-tag {
  font-size: 15px;
  padding: 2px 16px;
  border-radius: 12px;
  font-weight: 500;
}
.custom-edit-form {
  padding: 10px 0 0 0;
}
.custom-edit-form .el-form-item {
  margin-bottom: 18px;
}
.custom-edit-form .el-input {
  width: 260px;
}
.custom-edit-form .el-select {
  width: 120px;
}
.custom-textarea .el-textarea__inner {
  border-radius: 8px;
  background: #f8fafd;
  border: 1.5px solid #a0cfff;
  font-size: 16px;
  min-height: 80px;
  resize: vertical;
  padding: 10px 14px;
  transition: border-color 0.2s;
}
.custom-textarea .el-textarea__inner:focus {
  border-color: #409eff;
  background: #f0f8ff;
}

.handover-content {
  padding: 20px 0;
}

.handover-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 